package com.app.controller.imessage;

import com.app.model.cache.UserInfoToCache;
import com.app.model.main.MeetRecord;
import com.app.model.main.MessageRecord;
import com.app.model.main.UserInfo;
import com.app.model.response.BaseUserInfo;
import com.app.model.response.RetCode;
import com.app.model.response.RetStatus;
import com.app.repository.interfaces.*;
import com.app.service.ResponseService;
import com.app.service.imessage.IMService;
import com.app.service.imessage.ImessageService;
import com.app.support.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * Created by Lichaojie on 2017/4/7. It's a beautiful day.
 */

@RequestMapping(value = "/imessage")
@RestController
public class IMController {

    @Autowired
    private ResponseService responseService;
    @Autowired
    private IMService imService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MeetRecordMapper meetRecordMapper;
    @Autowired
    private MessageRecordMapper messageRecordMapper;
    @Autowired
    private ImessageService imessageService;


    @RequestMapping(value = "/getSig")
    public RetStatus getSig(@RequestBody String parameter){
        return imessageService.getSig(parameter);
    }

    /**
     * 获取私信列表的用户信息
     * @param parameter
     * @return
     */
    @RequestMapping(value = "/getUserInfo")
    public RetStatus getUserInfo(@RequestBody String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String idStr = (String)paraMap.get("idList");
        String[] idArray = idStr.split(",");

        List<BaseUserInfo> resultList = new ArrayList<>();

        for (String str : idArray){
            long userId = Long.parseLong(str);
            if(userId < 1 || userId > userMapper.getMaxId()){
                return responseService.doResponse(218);
            }
            BaseUserInfo baseUserInfo = new BaseUserInfo();

            String key = "userInfo" + userId ;
            if(redisUtil.exists(key)){
                UserInfoToCache value = redisUtil.get(key);
                baseUserInfo.setUserId(userId)
                        .setAvator(value.getAvator())
                        .setNickName(value.getNickName());
            }else {
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
                if(userInfo == null){
                    return responseService.doResponse(200);
                }
                baseUserInfo.setUserId(userId)
                        .setNickName(userInfo.getNickName())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin());
            }
            resultList.add(baseUserInfo);
        }

        if(idArray.length == resultList.size()){
            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(200);
        }

    }

    /**
     * 提交用户的线下见面记录
     * @param parameter
     * @return
     */
    @RequestMapping(value = "/putMeetRecord")
    public RetStatus putMeetRecord(@RequestBody String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int receiverId = (int)paraMap.get("receiverId");
        int senderId = (int)paraMap.get("senderId");
        String time = (String)paraMap.get("time");
        int isReceived = (int)paraMap.get("isReceived");

        MeetRecord meetRecord = new MeetRecord();
        meetRecord.setReceiverId((long)receiverId)
                .setSenderId((long)senderId)
                .setTime(time)
                .setIsReceived((byte)isReceived);

        if(meetRecordMapper.insertSelective(meetRecord) == 1){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(200);
        }
    }

    @RequestMapping(value = "/putMessageRecord")
    public RetStatus putMessageRecord(@RequestBody String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int receiverId = (int)paraMap.get("receiverId");
        int senderId = (int)paraMap.get("senderId");
        String time = (String)paraMap.get("time");

        Calendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(Long.parseLong(time));

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        String dateString = "" + year + (month < 10 ? "0" + month : month) + (date < 10 ? "0" + date : date);

        List<MessageRecord> messageRecordList = new ArrayList<>();
        List<MessageRecord> list1 = messageRecordMapper.selectByReceiverId((long)receiverId);
        List<MessageRecord> list2 = messageRecordMapper.selectBySenderId((long)senderId);
        messageRecordList.addAll(list1);
        messageRecordList.addAll(list2);

        for (MessageRecord messageRecord : messageRecordList){
            String ntime = messageRecord.getTime();
            if(dateString.equals(ntime)){//当天该两个用户有过私信往来
                return responseService.doResponse(100);
            }
        }

        MessageRecord messageRecord = new MessageRecord();
        messageRecord.setReceiverId((long)receiverId)
                .setSenderId((long)senderId)
                .setTime(dateString);
        if(messageRecordMapper.insertSelective(messageRecord) == 1){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(200);
        }
    }

    @RequestMapping(value = "/pushAllUser")
    public RetStatus pushAllUser() throws Exception{
        List<UserInfo> userInfoList = userInfoMapper.getAll();
        String idListStr = "";
        for (UserInfo userInfo : userInfoList){
            boolean flag = imService.setInfo(userInfo);
//            if(!flag){
//                while (!flag){
//                    flag = imService.setInfo(userInfo);
//                }
//            }
            if(!flag) idListStr += (userInfo.getId() + ",");
        }
        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(idListStr);

        return retStatus;
    }

    @RequestMapping(value = "/pushUser")
    public RetStatus pushUser(@RequestBody String parameter) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey((long)userId);

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(200)
                .setMessage(RetCode.getMessage(200));

        if(imService.importInfo(userInfo)){
            if(imService.setInfo(userInfo)){
                return responseService.doResponse(100);
            }else {
                retStatus.setBody("setInfo failed!");
            }
        }else {
            retStatus.setBody("importInfo failed!");
        }

        return retStatus;
    }

    @RequestMapping(value = "/getInfo")
    public RetStatus getInfo(@RequestBody String parameter)throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");

        return imService.getInfo((long)userId);
    }

    @RequestMapping(value = "/sendMessage")
    public RetStatus sendMessage(@RequestBody String parameter)throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int from = (int)paraMap.get("from");
        int to = (int)paraMap.get("to");

        if(imService.sendMessage(from,to)){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(324);
        }
    }
}
